try:
    import pygame
except ImportError:
    pass

import os
from pyre.data import info

class SpriteInfo(info.InfoDB):

    def __init__(self, filename):
        info.InfoDB.__init__(self, filename, tilesize=int,
                                             index=info.parse_tuple)

    def build_sprite_cache(self, rescale_size=None, file_prefix=''):
        sheets = {}
        for name in (key for key in self.data if not key.isdigit()):
            filename = os.path.join(file_prefix, self[name]['filename'])
            sheet_data = pygame.image.load(filename).convert_alpha()
            sheets[name] = sheet_data, self[name]['tilesize']

        sprites = {}
        for sprite_id in (key for key in self.data if key.isdigit()):
            sheet, tilesize = sheets[self[sprite_id]['sheet']]
            tile_x, tile_y = self[sprite_id]['index']
            rect = tile_x * tilesize, tile_y * tilesize, tilesize, tilesize
            sprite = sheet.subsurface(rect)
            if tilesize != rescale_size and rescale_size is not None:
                new_size = rescale_size, rescale_size
                sprite = pygame.transform.scale(sprite, new_size)
            sprites[int(sprite_id)] = sprite

        return sprites
